package lightrain.code.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;



import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;


/**
 * @author Yue hanjiang
 */
@SuppressWarnings("unchecked")
public class NObject<N extends Object> extends LinkedHashMap<String, Object>{
	

	private static final long serialVersionUID = -3044936096189536682L;

	/**
	 * 获取字段数据
	 * @auther Y.hj
	 * @param name 
	 * @return
	 */
	public <T> T get(String name){
		return (T) super.get(name);
	}
	
	/**
	 * 获取字段数据
	 * @auther Y.hj
	 * @param name 名字
	 * @param defaultValue 默认值
	 * @return
	 */
	public <T> T get(String name,Object defaultValue){
		if(StringUtils.isEmpty(get(name))){
			return (T) defaultValue;
		}
		return get(name);
	}
	
	public Attr attr(String name){
		return new Attr(super.get(name));
	}
	
	public N set(String key,Object value){
		super.put(key, value);
		return (N) this;
	}
	
	public N setAll(Map<String, Object> map){
		super.putAll(map);
		return (N) this;
	}
	
	public N set(Object...objects){
		for (int i = 0; i < objects.length; i++) {
			if(i%2 == 0){
				set(objects[i].toString(), objects[i+1]);
			}
		}
		return (N) this;
	}
	
	public N put(String key,Object value){
		return set(key, value);
	}
	
	public <T extends NObject<?>>  T copyToNobject(Class<T> classType,String...names){
			try {
				T nmap = classType.newInstance();
				if(names.length > 0){
					for (String name : names) {
						nmap.set(name, get(name));
					}
				}else{
					nmap.putAll(this);
				}
				return nmap;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	}
	
	public <T> T copyToBean(Class<T> beanClass,String...fields){
		T bean = BeanUtils.instantiate(beanClass);
		try {
			for (String field : fields) {
				PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(beanClass, field);
				Method method = descriptor.getWriteMethod();
				method.invoke(bean,get(field));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	
	public NObject(Object...objects){
		set(objects);
	}

	
	public String toJSONString(){
		return JSON.toJSONString(this);
	}
	
	public NObject() {
		super();
	}

	public NObject(int initialCapacity, float loadFactor, boolean accessOrder) {
		super(initialCapacity, loadFactor, accessOrder);
	}

	public NObject(int initialCapacity, float loadFactor) {
		super(initialCapacity, loadFactor);
	}

	public NObject(int initialCapacity) {
		super(initialCapacity);
	}

	public NObject(Map<? extends String, ? extends Object> m) {
		super(m);
	}
	
	public N removes(String...strings){
		for (int i = 0; i < strings.length; i++) {
			remove(strings[i]);
		}
		return (N) this;
	}
	
}
